import { defineStore } from 'pinia';
import { differenceInDays } from 'date-fns';
import { getDefaultAfterDate, getDefaultBeforeDate } from '../utils/date';

type CheckoutState = {
  mode: 1 | 2;
  startDate: string;
  endDate: string;
  roomsNumber: number;
  adultsNumber: number;
  childrenNumber: number;
  babysNumber: number;
  currency: string;
  isLoggedIn: boolean;
};

export const useCheckoutStore = defineStore('checkout', {
  state: () => {
    return {
      /**
       * 1: 民宿 2: 短租
       */
      mode: 1,
      startDate: getDefaultBeforeDate(),
      endDate: getDefaultAfterDate(),
      roomsNumber: 1,
      adultsNumber: 1,
      childrenNumber: 0,
      babysNumber: 0,
      currency: 'JPY',
      isLoggedIn: false
    } as CheckoutState;
  },
  getters: {
    /**
     * 入住天数
     */
    daysNumber: (state) => {
      const startDate = new Date(state.startDate);
      const endDate = new Date(state.endDate);
      return differenceInDays(endDate, startDate);
    },
    /**
     * 入住人数
     */
    bookersNumber: (state) => {
      return state.adultsNumber + state.childrenNumber + state.babysNumber;
    }
  },
  actions: {
    setMode(mode: 1 | 2) {
      this.mode = mode;
      this.setBookersNumber(1, 0, 0);
    },
    setDate(
      startDate: string = getDefaultBeforeDate(),
      endDate: string = getDefaultAfterDate(getDefaultBeforeDate(), 1)
    ) {
      this.startDate = startDate;
      this.endDate = endDate;
    },
    setBookersNumber(adultsNumber: number, childrenNumber: number, babysNumber: number) {
      this.adultsNumber = adultsNumber;
      this.childrenNumber = childrenNumber;
      this.babysNumber = babysNumber;
    },
    setCurrency(currency: string) {
      this.currency = currency;
    }
  }
});
